package com.iqilu.ksd.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.tedcoder.wkvideoplayer.constant.VideoType;
import com.android.tedcoder.wkvideoplayer.model.Video;
import com.android.tedcoder.wkvideoplayer.model.VideoUrl;
import com.android.tedcoder.wkvideoplayer.view.MediaController;
import com.android.tedcoder.wkvideoplayer.view.SuperVideoPlayer;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.NewsHotAdapter;
import com.iqilu.ksd.bean.GalleryItemBean;
import com.iqilu.ksd.bean.NewsBean;
import com.iqilu.ksd.bean.NewsItemBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.NewsType;
import com.iqilu.ksd.constant.SharePlatform;
import com.iqilu.ksd.event.StopPlayRadioEvent;
import com.iqilu.ksd.event.StopPlayVideoEvent;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.NetworkUtils;
import com.iqilu.ksd.utils.ScreenUtils;
import com.iqilu.ksd.utils.ShareUtils;
import com.iqilu.ksd.widget.MyListView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 新闻内容页
 * <p>
 * Created by coofee on 2015/11/6.
 */
public class NewsDetailActivity extends BaseActivity implements View.OnClickListener {

    private static String TAG = "NewsDetailActivity";

    private int newsId;
    private int catId;
    private Boolean fromJPush = false;
    private MyApplication application;
    private NewsBean data;
    private UserBean user;
    private ArrayList<NewsItemBean> hotList;
    private NewsHotAdapter adapter;

    private RelativeLayout layPlayer;
    private LinearLayout layContent;
    private WebView wvContent;
    private ImageView btClose;
    private ImageView btBack;
    private ImageView btShare;
    private ImageView btLove;
    private LinearLayout layComment;
    private TextView tvComment;
    private LinearLayout layLike;
    private ImageView imgLike;
    private TextView tvLike;
    private MyListView lvList;
    private ProgressBar pbBar;
    private TextView tvTitle;
    private TextView tvDate;
    private TextView tvCopyfrom;
    private SuperVideoPlayer superVideoPlayer;
    private ScrollView layScroll;
    private LinearLayout layFooter;
    private RelativeLayout layLoading;

    private SimpleDraweeView imgAD;
    private RelativeLayout laySubs;
    private SimpleDraweeView imgThumb;
    private TextView tvCatname;
    private ImageView btSubs;

    private ImageView btWeibo;
    private ImageView btWechatmoments;
    private ImageView btWechat;
    private ImageView btQQ;

    private int mWidth;
    private int mHeight;
    private int ADHeight;
    private int screenHeight;

    private static final int OPEN_PLAYER = 2001;
    private static final int REQUEST_LOGIN = 2002;

    private SuperVideoPlayer.VideoPlayCallbackImpl mVideoPlayCallback = new SuperVideoPlayer.VideoPlayCallbackImpl() {
        @Override
        public void onCloseVideo() {
        }

        @Override
        public void onSwitchPageType() {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                superVideoPlayer.setPageType(MediaController.PageType.SHRINK);
                toggleHide(false);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                superVideoPlayer.setPageType(MediaController.PageType.EXPAND);
                toggleHide(true);
            }
        }

        @Override
        public void onPlayFinish() {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ShareSDK.initSDK(this);
        setContentView(R.layout.activity_newsdetail);
        application = (MyApplication) getApplication();
        user = application.getUser();
        Intent intent = getIntent();
        newsId = intent.getIntExtra("id", 0);
        catId = intent.getIntExtra("catId", 0);
        fromJPush = intent.getBooleanExtra("fromJPush", false);
        adapter = new NewsHotAdapter(this);
        initView();
        lvList.setAdapter(adapter);
        lvList.setFocusable(false);
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = null;
                NewsItemBean item = hotList.get(position);
                if (item.getType().equals(NewsType.ARTICLE)) {
                    intent = new Intent(NewsDetailActivity.this, NewsDetailActivity.class);
                    intent.putExtra("id", item.getId());
                    intent.putExtra("catId", item.getCatid());
                } else if (item.getType().equals(NewsType.GALLERY) || item.getType().equals(NewsType.PHOTO)) {
                    intent = new Intent(NewsDetailActivity.this, GalleryActivity.class);
                    intent.putExtra("id", item.getId());
                    intent.putExtra("catId", item.getCatid());
                    intent.putExtra("position", 0);
                } else if (item.getType().equals(NewsType.AD) || item.getType().equals(NewsType.URL)) {
                    intent = new Intent(NewsDetailActivity.this, ADActivity.class);
                    intent.putExtra("title", item.getTitle());
                    intent.putExtra("type", item.getType());
                    intent.putExtra("adUrl", item.getUrl());
                    if (item.getType().equals(NewsType.AD)) {
                        intent.putExtra("shareicon", item.getShareicon());
                    } else {
                        intent.putExtra("thumb", item.getThumb());
                    }
                } else if (item.getType().equals(NewsType.LIVE)) {
                    intent = new Intent(NewsDetailActivity.this, LiveActivity.class);
                    intent.putExtra("id", item.getId());
                } else if (item.getType().equals(NewsType.CLUE)) {
                    intent = new Intent(NewsDetailActivity.this, PaikeActivity.class);
                    intent.putExtra("id", item.getId());
                }
                if (intent != null) {
                    startActivity(intent);
                }
            }
        });
        initWebView();
        superVideoPlayer.setVideoPlayCallback(mVideoPlayCallback);
        mWidth = ScreenUtils.getScreenWidth(this);
        screenHeight = ScreenUtils.getScreenHeight(this);
        mHeight = mWidth * 3 / 4;
        ViewGroup.LayoutParams params = layPlayer.getLayoutParams();
        params.height = mHeight;
        layPlayer.setLayoutParams(params);
        ADHeight = mWidth * 120 / 525;
        ViewGroup.LayoutParams adParams = imgAD.getLayoutParams();
        adParams.height = ADHeight;
        imgAD.setLayoutParams(adParams);
    }

    private void initView() {
        layPlayer = getView(R.id.lay_player);
        layContent = getView(R.id.lay_content);
        wvContent = getView(R.id.wv_content);
        btClose = getView(R.id.bt_close);
        btBack = getView(R.id.bt_back);
        btShare = getView(R.id.bt_share);
        btLove = getView(R.id.bt_love);
        layComment = getView(R.id.lay_comment);
        tvComment = getView(R.id.tv_comment);
        layLike = getView(R.id.lay_like);
        imgLike = getView(R.id.img_like);
        tvLike = getView(R.id.tv_like);
        lvList = getView(R.id.lv_list);
        pbBar = getView(R.id.pb_bar);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        tvDate = getView(R.id.tv_date);
        tvCopyfrom = getView(R.id.tv_copyfrom);
        layScroll = getView(R.id.lay_scroll);
        layFooter = getView(R.id.lay_footer);
        layLoading = getView(R.id.lay_loading);
        superVideoPlayer = getView(R.id.superVideoPlayer);

        imgAD = getView(R.id.img_ad);
        laySubs = getView(R.id.lay_subs);
        imgThumb = getView(R.id.img_thumb);
        tvCatname = getView(R.id.tv_catname);
        setZHTypeface(tvCatname);
        btSubs = getView(R.id.bt_subs);

        btWeibo = getView(R.id.bt_weibo);
        btWechat = getView(R.id.bt_wechat);
        btWechatmoments = getView(R.id.bt_wechatmoments);
        btQQ = getView(R.id.bt_qq);

        btClose.setOnClickListener(this);
        btBack.setOnClickListener(this);
        btWeibo.setOnClickListener(this);
        btWechat.setOnClickListener(this);
        btWechatmoments.setOnClickListener(this);
        btQQ.setOnClickListener(this);
        btShare.setOnClickListener(this);
        layComment.setOnClickListener(this);
        btLove.setOnClickListener(this);
        layLike.setOnClickListener(this);
        layPlayer.setOnClickListener(this);
        btSubs.setOnClickListener(this);
        imgThumb.setOnClickListener(this);
        imgAD.setOnClickListener(this);
    }

    private void initWebView() {
        WebSettings settings = wvContent.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        String ua = settings.getUserAgentString();
        settings.setUserAgentString(ua + ";shandian/android");
        wvContent.addJavascriptInterface(new JsObject(getApplicationContext()), "imagelistner");
        wvContent.setWebChromeClient(new MyWebChromeClient());
        wvContent.setWebViewClient(new MyWebViewClient());
        getContent();
    }

    /***
     * 恢复屏幕至竖屏
     */
    private void resetPageToPortrait() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            superVideoPlayer.setPageType(MediaController.PageType.SHRINK);
            toggleHide(false);
        }
    }

    /***
     * 旋转屏幕之后回调
     *
     * @param newConfig newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (null == superVideoPlayer) return;
        ViewGroup.LayoutParams params = layPlayer.getLayoutParams();
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().invalidate();
//            superVideoPlayer.getLayoutParams().height = mWidth;
//            superVideoPlayer.getLayoutParams().width = screenHeight;
            params.height = mWidth;
            params.width = screenHeight;
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
//            superVideoPlayer.getLayoutParams().height = mHeight;
//            superVideoPlayer.getLayoutParams().width = mWidth;
            params.height = mHeight;
            params.width = mWidth;
        }
        layPlayer.setLayoutParams(params);
    }

    private void toggleHide(boolean hide) {
        int status;
        if (hide) {
            status = View.GONE;
        } else {
            status = View.VISIBLE;
        }
        btClose.setVisibility(status);
        layFooter.setVisibility(status);
        layScroll.setVisibility(status);
    }

    // 收藏
    private void toFavorite() {
        if (user == null || user.getId() == 0) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, REQUEST_LOGIN);
            return;
        }
        if (data.getFavorited() == 1) {
            delFavorite();
        } else {
            addFavorite();
        }
    }

    // 点赞
    void toLike() {
        if (user == null || user.getId() == 0) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, REQUEST_LOGIN);
            return;
        }
        if (data.getLiked() != 1) {
            addLike();
        } else {
            delLike();
        }
    }

    private void toShare(SharePlatform sharePlatform) {
        if (data == null) return;
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(data.getTitle());
        sp.setTitleUrl(data.getShareurl()); // 标题的超链接
        sp.setText(data.getDescription());
        sp.setSiteUrl(data.getShareurl());
        sp.setUrl(data.getShareurl());
        sp.setImageUrl(data.getThumb());//分享网络图片
        sp.setSite(getString(R.string.app_name));
        if (sharePlatform == null) {
            ShareUtils.getInstance().setShareParams(this, sp).show();
        } else {
            ShareUtils.getInstance().setShareParams(this, sp).toShare(sharePlatform);
        }
    }

    private void closeVideo() {
        superVideoPlayer.pausePlay(false);
//        superVideoPlayer.setVisibility(View.GONE);
        layPlayer.setVisibility(View.GONE);
        btClose.setVisibility(View.GONE);
    }

    //
//    // 评论
    private void toComment() {
        Intent intent = new Intent(this, CommentActivity.class);
        intent.putExtra("articleid", data.getId());
        intent.putExtra("catid", data.getCatid());
        intent.putExtra("type", data.getType());
        startActivity(intent);
    }

    public void initBottom() {
        if (data.getFavorited() != 0 && user != null) {
            btLove.setImageResource(R.drawable.bt_footer_love_blue);
        }
        if (data.getLiked() != 0 && user != null) {
            imgLike.setImageResource(R.drawable.bt_like_orange);
        }
//        tvLove.setText(""+data.getL);
        tvComment.setText("" + data.getCommentnum());
        tvLike.setText("" + data.getLikenum());
    }

    private void initHead() {
        tvTitle.setText("" + data.getTitle());
        tvDate.setText("" + data.getDate());
        tvCopyfrom.setText("" + data.getCopyfrom());
    }

    private void initSubs() {
        if (data.getIssubscribecate() == 1) {
            laySubs.setVisibility(View.VISIBLE);
            imgThumb.setImageURI(Uri.parse("" + data.getCatthumb()));
            tvCatname.setText("" + data.getCatname());
            if (data.getSubscribed() == 1) {
                btSubs.setImageResource(R.drawable.bt_subscribed);
            } else {
                btSubs.setImageResource(R.drawable.bt_subscribe);
            }
        }
    }

    private void toSubscribe() {
        if (user == null || user.getId() < 1) {
//            Toast.makeText(this, R.string.not_login, Toast.LENGTH_SHORT).show();
            startActivityForResult(new Intent(NewsDetailActivity.this, LoginActivity.class), REQUEST_LOGIN);
            return;
        }
        if (data.getSubscribed() == 1) {
            delSubscribe();
        } else {
            addSubscribe();
        }
    }

    private void jump2Subscribe() {
        Intent intent = new Intent(this, SubsDetailActivity.class);
        intent.putExtra("catid", data.getCatid());
        startActivity(intent);
    }

    private void jump2ad() {
        Intent intent = new Intent(this, ADActivity.class);
        intent.putExtra("title", data.getTitle());
        intent.putExtra("type", data.getAdtype());
        intent.putExtra("adUrl", data.getAdurl());
        if (data.getAdtype().equals(NewsType.AD)) {
            intent.putExtra("shareicon", data.getAdshareicon());
        } else {
            intent.putExtra("thumb", data.getAdthumb());
        }
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_love:
                toFavorite();
                break;
            case R.id.lay_comment:
                toComment();
                break;
            case R.id.lay_like:
                toLike();
                break;
            case R.id.bt_share:
                toShare(null);
                break;
            case R.id.bt_weibo:
                toShare(SharePlatform.WEIBO);
                break;
            case R.id.bt_wechatmoments:
                toShare(SharePlatform.WECHATMOMENTS);
                break;
            case R.id.bt_wechat:
                toShare(SharePlatform.WECHAT);
                break;
            case R.id.bt_qq:
                toShare(SharePlatform.QQ);
                break;
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_close:
                closeVideo();
                break;
            case R.id.bt_subs:
                toSubscribe();
                break;
            case R.id.img_thumb:
                jump2Subscribe();
                break;
            case R.id.img_ad:
                jump2ad();
                break;
            default:
                break;
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == OPEN_PLAYER) {
                Bundle bundle = msg.getData();
                String url = bundle.getString("url");
                if (NetworkUtils.isAvailable(NewsDetailActivity.this) && !NetworkUtils.isWifiConnected(NewsDetailActivity.this)) {
                    showSelectDialog(url);
                } else {
                    toPlay(url);
                }
            }
        }
    };

    // js通信接口
    public class JsObject {

        private Context context;

        public JsObject(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void openImage(String img, String position) {
            Log.i(TAG, "openImage position=" + position);
            String[] imgs = img.split(",");
            ArrayList<GalleryItemBean> gallery = new ArrayList<GalleryItemBean>();
            for (String s : imgs) {
                GalleryItemBean galleryItemBean = new GalleryItemBean();
                galleryItemBean.setImg(s);
                gallery.add(galleryItemBean);
            }
            data.setGallery(gallery);
            Intent intent = new Intent(context, GalleryActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("news", data);
            intent.putExtras(bundle);
            intent.putExtra("position", Integer.valueOf(position));
            intent.putExtra("fromNews", true);
            startActivity(intent);
        }

        @JavascriptInterface
        public void openPlayer(String url) {
            Log.i(TAG, "openPlayer=" + url);
            Message msg = new Message();
            msg.what = OPEN_PLAYER;
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            msg.setData(bundle);
            handler.sendMessage(msg);
        }
    }

    private void addImageClickListner() {
        wvContent.loadUrl("javascript:(function(){"
                + "var objs = document.getElementsByTagName(\"img\");"
                + "var imgurl=''; "
                + "var j = 0;"
                + "for(var i=0;i<objs.length;i++)  "
                + "{"
                + "if(objs[i].getAttribute('name') == 'videotag') continue;"
                + "imgurl+=objs[i].src+',';"
                + "objs[i].setAttribute('position',j);"
                + "j++;"
                + "    objs[i].onclick=function()  " + "    {  "
                + "        window.imagelistner.openImage(imgurl,this.getAttribute('position'));  "
                + "    }  "
                + "}"
                + "})()");
    }

    // 监听
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageFinished(view, url);
            pbBar.setVisibility(View.GONE);
            // html加载完成之后，添加监听图片的点击js函数
            addImageClickListner();
            wvContent.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            pbBar.setVisibility(View.GONE);
        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress != 100) {
                pbBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    private void showSelectDialog(final String url) {
        new AlertDialog.Builder(this).setTitle(com.android.tedcoder.wkvideoplayer.R.string.app_name)
                .setMessage(com.android.tedcoder.wkvideoplayer.R.string.not_wifi)
                .setPositiveButton(com.android.tedcoder.wkvideoplayer.R.string.ensure, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toPlay(url);
                    }
                })
                .setNegativeButton(com.android.tedcoder.wkvideoplayer.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setCancelable(true)
                .show();
    }

    private void toPlay(String url) {
//        superVideoPlayer.setMinimumHeight(mHeight);
//        superVideoPlayer.setVisibility(View.VISIBLE);
        layPlayer.setVisibility(View.VISIBLE);
        superVideoPlayer.setAutoHideController(true);
        Video video = new Video();
        VideoUrl videoUrl = new VideoUrl();
        videoUrl.setFormatName("480P");
        videoUrl.setFormatUrl(url);
        ArrayList<VideoUrl> arrayList1 = new ArrayList<>();
        arrayList1.add(videoUrl);
        video.setVideoName("" + data.getTitle());
        video.setVideoUrl(arrayList1);
        video.setmVideoType(VideoType.VIDEO_ONLINE);
        ArrayList<Video> videoArrayList = new ArrayList<>();
        videoArrayList.add(video);
        superVideoPlayer.loadMultipleVideo2(videoArrayList, 0, 0, 0);
        btClose.setVisibility(View.VISIBLE);
        EventBus.getDefault().post(new StopPlayVideoEvent());
        EventBus.getDefault().post(new StopPlayRadioEvent());
    }

    private void getContent() {
        String url = Api.URL_ARTICLE + "?id=" + newsId + "&catid=" + catId;
        Log.i(TAG, "url=" + url);
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                layLoading.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(NewsDetailActivity.this, R.string.content_null, Toast.LENGTH_SHORT).show();
//                layLoading.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(String response, int id) {
                layLoading.setVisibility(View.GONE);
                data = JSONUtils.requestDetail(response, "data", NewsBean.class);
                if (data == null) {
                    Toast.makeText(NewsDetailActivity.this, R.string.content_null, Toast.LENGTH_SHORT).show();
                    layLoading.setVisibility(View.VISIBLE);
//                    finish();
                    return;
                }
                initHead();
                initBottom();
                if (!TextUtils.isEmpty(data.getAdurl())) {
                    imgAD.setImageURI(Uri.parse(data.getAdthumb()));
                    imgAD.setVisibility(View.VISIBLE);
                }
                wvContent.loadDataWithBaseURL(null, data.getContent(), "text/html", "utf-8", null);
                wvContent.setVisibility(View.VISIBLE);
                initSubs();
                getHot();
            }
        });
    }

    private void getIsSubs() {
        String url = Api.URL_ARTICLE + "?id=" + newsId + "&catid=" + catId;
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                data = JSONUtils.requestDetail(response, "data", NewsBean.class);
                if (data != null) {
                    initSubs();
                }
            }
        });
    }

    private void getHot() {
        String url = Api.URL_ARTICLE_HOT + "?id=" + newsId + "&catid=" + data.getCatid() + "&pagesize=4";
        Log.i(TAG, "getHot url=" + url);
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                hotList = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<NewsItemBean>>() {
                });
                adapter.setData(hotList);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void addSubscribe() {
        String url = Api.URL_SUBSCRIBE + "?catid=" + data.getCatid() + "&catname=" + data.getCatname() + "&type=article";
        OkHttpUtils
                .put()
                .url(url)
                .requestBody(RequestBody.create(null, "something"))
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(NewsDetailActivity.this, R.string.my_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response, "status", 0);
                        if (status == 1) {
                            data.setSubscribed(1);
                            btSubs.setImageResource(R.drawable.bt_subscribed);
                            Toast.makeText(NewsDetailActivity.this, R.string.my_add_success, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(NewsDetailActivity.this, R.string.my_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void delSubscribe() {
        String url = Api.URL_SUBSCRIBE + "?catid=" + data.getCatid() + "&type=article";
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(NewsDetailActivity.this, R.string.my_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
                    data.setSubscribed(0);
                    btSubs.setImageResource(R.drawable.bt_subscribe);
                    Toast.makeText(NewsDetailActivity.this, R.string.my_del_success, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(NewsDetailActivity.this, R.string.my_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 添加收藏
    private void addFavorite() {
        String url = Api.URL_FAVORITE;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("articleid", "" + data.getId())
                .addParams("title", "" + data.getTitle())
                .addParams("catid", "" + data.getCatid())
                .addParams("type", "" + data.getType())
                .addParams("url", "" + data.getUrl())
                .addParams("thumb", "" + data.getThumb())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(NewsDetailActivity.this, R.string.favorite_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response, "status", 0);
                        if (status == 1) {
                            Toast.makeText(NewsDetailActivity.this, R.string.favorite_add_success, Toast.LENGTH_SHORT).show();
                            btLove.setImageResource(R.drawable.bt_footer_love_blue);
                            data.setFavorited(1);
                        } else {
                            Toast.makeText(NewsDetailActivity.this, R.string.favorite_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    // 删除收藏
    private void delFavorite() {
        int id = data.getId();
        String type = data.getType();
        String url = Api.URL_FAVORITE + "?articleid=" + id + "&type=" + type;
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(NewsDetailActivity.this, R.string.favorite_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
                    Toast.makeText(NewsDetailActivity.this, R.string.favorite_del_success, Toast.LENGTH_SHORT).show();
                    btLove.setImageResource(R.drawable.bt_footer_love);
                    data.setFavorited(0);
                } else {
                    Toast.makeText(NewsDetailActivity.this, R.string.favorite_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 点赞
    private void addLike() {
        String url = Api.URL_ARTICLE_LIKE + "?id=" + data.getId() + "&catid=" + data.getCatid() + "&type=" + data.getType();
        String query = "id=" + data.getId() + "&catid=" + data.getCatid() + "&type=" + data.getType();
        OkHttpUtils
                .put()
                .url(url)
                .requestBody(query)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(NewsDetailActivity.this, R.string.like_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response, "status", 0);
                        if (status == 1) {
                            Toast.makeText(NewsDetailActivity.this, R.string.like_add_success, Toast.LENGTH_SHORT).show();
                            imgLike.setImageResource(R.drawable.bt_like_orange);
                            int count = Integer.valueOf("" + tvLike.getText()) + 1;
                            tvLike.setText("" + count);
                            data.setLiked(1);
                        } else {
                            Toast.makeText(NewsDetailActivity.this, R.string.like_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    // 取消点赞
    private void delLike() {
        String url = Api.URL_ARTICLE_LIKE + "?id=" + data.getId() + "&catid=" + data.getCatid() + "&type=" + data.getType();
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(NewsDetailActivity.this, R.string.like_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
                    Toast.makeText(NewsDetailActivity.this, R.string.like_del_success, Toast.LENGTH_SHORT).show();
                    imgLike.setImageResource(R.drawable.bt_like);
                    int count = Integer.valueOf("" + tvLike.getText()) - 1;
                    count = Math.max(0, count);
                    tvLike.setText("" + count);
                    data.setLiked(0);
                } else {
                    Toast.makeText(NewsDetailActivity.this, R.string.like_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void back() {
        if (fromJPush && !application.getMainStarted()) {
            startActivity(new Intent(NewsDetailActivity.this, MainActivity.class));
        }
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_LOGIN:
                    user = application.getUser();
                    getIsSubs();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            resetPageToPortrait();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        layContent.removeView(wvContent);
        wvContent.removeAllViews();
        wvContent.destroy();
    }
}
